package com.daemon;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Process {
    public static List<String> cLSprInfo = new ArrayList<>();
    public static void main(String[] args) {







    }
    public static void logic(){
        CLSpr("powershell.exe \"Get-WmiObject -Class Win32_Process | Select-Object -Property ProcessId, Name, Status, CommandLine | ConvertTo-Csv -NoTypeInformation\" ");
        CLSHpr();

        // item
        File file = new File(".","config.txt");
        if (file.exists()) {
            try {
                //System.out.println("file = " + file.getPath());
                InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
                BufferedReader bufferedReader = new BufferedReader(reader);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    //buffereReader.readLine()按行读取写成字符串
                    String[] strs=lineTxt.split("\\\\");
                    String str = strs[strs.length - 1];
                    String fileName1 = str.replaceAll(".bat", "");
                    System.out.println(lineTxt);
                    System.out.println(fileName1);

                    // itme
                    //String fileName = "34test_task222222.py";
                    String fileName = fileName1;
                    //String fileNameCmd = "\"D:\\temp\\txt_translation_task\\34test_task222222.py.bat\"";
                    String fileNameCmd = lineTxt;
                    boolean exist = checkWhetherExist(fileName);
                    if(!exist){
                        System.out.println("没有找到 "+fileName+" 的相关进程，正在执行："+fileNameCmd);
                        CLSTaskExecute(fileNameCmd);
                        System.out.println("执行成功："+fileNameCmd+"\n");
                    }else{
                        System.out.println("发现 "+fileName+" 的相关进程，守护成功！");
                    }
                }
                reader.close();
                cLSprInfo.clear();
            }catch (IOException ioException){
                cLSprInfo.clear();
            }
        }else{
            System.out.println(" 配置文件不存在 path:"+file.getPath());
        }
        cLSprInfo.clear();


    }


    /***
     * 检查是否存在运行的文件进程
     * @param fileName
     * @return
     */
    public static boolean checkWhetherExist(String fileName){
        List<HashMap<String, String>> cLSprHInfo = new ArrayList<>();
        cLSprInfo.forEach(info ->{
            HashMap<String, String> hashMap = new HashMap<>();
            String[] split = info.split(",");
            String ProcessId = "";
            try {
                ProcessId = split[0];
            }catch (ArrayIndexOutOfBoundsException ignored){}
            String Name = "";
            try {
                Name = split[1];
            }catch (ArrayIndexOutOfBoundsException ignored){}
            String Status = "";
            try {
                Status = split[2];
            }catch (ArrayIndexOutOfBoundsException ignored){}
            String CommandLine = "";
            try {
                CommandLine = split[3];
            }catch (ArrayIndexOutOfBoundsException ignored){}
            hashMap.put("ProcessId", ProcessId);
            hashMap.put("Name", Name);
            hashMap.put("Status", Status);
            hashMap.put("CommandLine", CommandLine);
            cLSprHInfo.add(hashMap);
            //System.out.println(ProcessId+"\t"+Name+"\t"+Status+"\t"+CommandLine);
        });

        for (int i = 0; i < cLSprHInfo.size(); i++) {
            if (null != cLSprHInfo.get(i).get("CommandLine") && !"".equals(cLSprHInfo.get(i).get("CommandLine")) && cLSprHInfo.get(i).get("CommandLine").contains(fileName)) {
                System.out.println(cLSprHInfo.get(i).get("ProcessId")+"\t"+cLSprHInfo.get(i).get("Name")+"\t"+cLSprHInfo.get(i).get("Status")+"\t"+cLSprHInfo.get(i).get("CommmandLine"));
                return true;
            }
        }

        return false;
    }


    /***
     * 解析数据
     */
    public static List<HashMap<String, String>> CLSHpr(){
        List<HashMap<String, String>> cLSprHInfo = new ArrayList<>();
        cLSprInfo.forEach(info ->{
            HashMap<String, String> hashMap = new HashMap<>();
            String[] split = info.split(",");
            String ProcessId = "";
            try {
                ProcessId = split[0];
            }catch (ArrayIndexOutOfBoundsException ignored){}
            String Name = "";
            try {
                Name = split[1];
            }catch (ArrayIndexOutOfBoundsException ignored){}
            String Status = "";
            try {
                Status = split[2];
            }catch (ArrayIndexOutOfBoundsException ignored){}
            String CommandLine = "";
            try {
                CommandLine = split[3];
            }catch (ArrayIndexOutOfBoundsException ignored){}
            hashMap.put("ProcessId", ProcessId);
            hashMap.put("Name", Name);
            hashMap.put("Status", Status);
            hashMap.put("CommandLine", CommandLine);
            cLSprHInfo.add(hashMap);
            //System.out.println(ProcessId+"\t"+Name+"\t"+Status+"\t"+CommandLine);
        });
        return cLSprHInfo;
    }


    /***
     * 执行命令
     * @param cls 命令
     * @return
     */
    public static String CLSpr(String cls){
        try {
            cLSprInfo = new ArrayList<>();
            cLSprInfo.clear();
            new CLSTask(cls).run();
        }catch (Exception e){}
        return null;
    }

    /***
     * 执行命令
     * @param cls 命令
     * @return
     */
    public static String CLSTaskExecute(String cls){
        try {
            Runnable runnable = new Runnable() {

                @Override
                public void run() {
                    try {
                        new CLSTaskExecute(cls).run();
                    }catch (RuntimeException runtimeException){
                        cLSprInfo.clear();
                        CLSpr("powershell.exe \"Get-WmiObject -Class Win32_Process | Select-Object -Property ProcessId, Name, Status, CommandLine | ConvertTo-Csv -NoTypeInformation\" ");
                        System.out.println(" 意外停止，清空缓存, 退出的程序："+cls);
                    }

                }
            };
            Thread thread = new Thread(runnable);
            thread.start();
        }catch (Exception e){}
        return null;
    }
}
